// IpAddress.cpp: implementation of the CIpAddress class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "IpAddress.h"

CIpAddress::CIpAddress(BYTE b1 /*= 0*/, BYTE b2 /*= 0*/, BYTE b3 /*= 0*/, BYTE b4 /*= 0*/, WORD wPort /*= 0*/)
{
	sockaddr_in& addr = *((sockaddr_in*)this);
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_un_b.s_b1 = b1;
	addr.sin_addr.S_un.S_un_b.s_b2 = b2;
	addr.sin_addr.S_un.S_un_b.s_b3 = b3;
	addr.sin_addr.S_un.S_un_b.s_b4 = b4;
	addr.sin_port = htons(wPort);
}

CIpAddress::CIpAddress(DWORD dwAddr, WORD wPort /*= 0*/)
{
	BYTE* p = (BYTE*)&dwAddr;
	sockaddr_in& addr = *((sockaddr_in*)this);
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_un_b.s_b1 = *p; p++;
	addr.sin_addr.S_un.S_un_b.s_b2 = *p; p++;
	addr.sin_addr.S_un.S_un_b.s_b3 = *p; p++;
	addr.sin_addr.S_un.S_un_b.s_b4 = *p; p++;
	addr.sin_port = htons(wPort);
}

CIpAddress::CIpAddress(LPCTSTR sIpAddr)
{
	CString sTemp[5];
	int nCount = 0;

	for (unsigned int i = 0; i < _tcslen(sIpAddr); i++)
	{
		if (sIpAddr[i] == _T('.') || sIpAddr[i] == ':')
		{
			nCount++;
			if (nCount > 4)
				break;
		}
		else
		{
			sTemp[nCount] += sIpAddr[i];
		}

	}

	sockaddr_in& addr = *((sockaddr_in*)this);
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_un_b.s_b1 = (BYTE)_ttol(sTemp[0]);
	addr.sin_addr.S_un.S_un_b.s_b2 = (BYTE)_ttol(sTemp[1]);
	addr.sin_addr.S_un.S_un_b.s_b3 = (BYTE)_ttol(sTemp[2]);
	addr.sin_addr.S_un.S_un_b.s_b4 = (BYTE)_ttol(sTemp[3]);
	addr.sin_port = htons((WORD)_ttol(sTemp[4]));
}

CString CIpAddress::ToString()
{
	CString sTemp;

	sockaddr_in& addr=*((sockaddr_in*)this);
	sTemp.Format(_T("%u.%u.%u.%u:%u"),
			addr.sin_addr.S_un.S_un_b.s_b1,
			addr.sin_addr.S_un.S_un_b.s_b2,
			addr.sin_addr.S_un.S_un_b.s_b3,
			addr.sin_addr.S_un.S_un_b.s_b4,
			ntohs(addr.sin_port));

	return sTemp;
}

CString CIpAddress::AddrToString()
{
	CString sTemp;

	sockaddr_in& addr=*((sockaddr_in*)this);
	sTemp.Format(_T("%u.%u.%u.%u"),
			addr.sin_addr.S_un.S_un_b.s_b1,
			addr.sin_addr.S_un.S_un_b.s_b2,
			addr.sin_addr.S_un.S_un_b.s_b3,
			addr.sin_addr.S_un.S_un_b.s_b4);

	return sTemp;
}

BOOL CIpAddress::CompareTo(CIpAddress& i)
{
	sockaddr_in& addr1=*((sockaddr_in*)this);
	sockaddr_in& addr2=*((sockaddr_in*)&i);

	return ((addr1.sin_addr.S_un.S_addr == addr2.sin_addr.S_un.S_addr) &&
			(addr1.sin_port == addr2.sin_port));
}